import axios from 'axios';
import store from '@/store';
import AsyncStorage from '@react-native-async-storage/async-storage';
import * as RootNavigation from './rootNavigation';
import {handleLogout} from '@/store/action/user';
import Toast from 'react-native-root-toast';
import {i18n} from '@/language/i18n';

// 基础地址
//let baseURL = global.$config.BASE_URL;
//let appCode = global.$config.APP_CODE;
import {APP_CODE as appCode, BASE_URL as baseURL} from '../../app.json';

const getLocalToken = async () => {
  const value = await AsyncStorage.getItem('token');
  if (value) {
    return JSON.parse(value).token;
  }
  return '';
};

const handleError = data => {
  const isUnauthorized =
    data?.data === 'Full authentication is required to access this resource';
  const isExpired = data?.data?.includes('Invalid token');

  const current = RootNavigation.getCurrentRoute();

  if ((isUnauthorized || isExpired) && current != 'login') {
    store.dispatch(handleLogout());
    RootNavigation.reset('Login');
  }
};

const showErrMsg = msg => {
  if (msg) {
    if (
      msg === 'Full authentication is required to access this resource' ||
      msg.includes('Invalid token')
    ) {
      msg = i18n.t('sys_reLogin');
      showErrMsg(msg);
    }
    Toast.show(msg, {
      duration: 1000,
      position: Toast.positions.CENTER,
    });
  }
};

const service = axios.create({
  baseURL,
  //  withCredentials: true,
  headers: {
    Accept: 'application/json',
    'Content-Type': 'application/json;charset=UTF-8',
    appCode: appCode,
    //    'Authorization': store.getState().user.auth,
  },
  timeout: 20000,
});

// 请求拦截器
service.interceptors.request.use(
  async config => {
    const localAuthStr = await getLocalToken();
    const token = store.getState().user.auth || localAuthStr;
    if (!config.headers.Authorization) {
      config.headers.Authorization = token;
    }
    if (config.url.indexOf('auth/oauth/token') > -1) {
      // 登录
      config.headers.Authorization = 'Basic aDNjOmgzYw==';
    }

    // 域账号登录 如果存在过期token 需清空
    if (config.url.includes('/public/ldap/login')) {
      // 删除 Authorization 头
      if (config.headers && config.headers.Authorization) {
        delete config.headers.Authorization;
      }
    }
    //    console.log('拦截请求:', config);
    return config;
  },
  error => {
    //    console.log('拦截请求错误:', error);
    return Promise.reject(error);
  },
);

// 响应拦截器
service.interceptors.response.use(
  response => {
    // console.log("拦截响应结果=============:", response)
    // 响应正确
    const code = response?.data?.code;
    if (response.status == 200) {
      if (!code || code == 200) {
        return Promise.resolve(response.data);
      }
    }
    handleError(response.data);
    if (response?.data?.msg || response?.data?.message) {
      let msg = response?.data?.msg || response?.data?.message;
      showErrMsg(msg);
    }
    handleError(response.data);
    return Promise.reject(response.data);
  },
  error => {
    // console.log('拦截响应结果 error=============:', error);
    if (error?.config?.url.indexOf('loginDevice/queryUserConfig') > -1) {
      // 避免多端登录接口报错
      return Promise.resolve({});
    }
    if (error.message.includes('timeout')) {
      // 判断请求异常信息中是否含有超时timeout字符串
      showErrMsg(i18n.t('sys_requestTimeoutTip'));
      return Promise.reject(error);
    }

    const data = error?.response?.data;
    if (data?.msg || data?.message) {
      showErrMsg(data.msg || data.message);
    } else {
      showErrMsg(error.message || i18n.tt('sys_serverErrorTip'));
    }
    handleError(error.response.data);
    return Promise.reject(error);
  },
);

/**
 * 封装get方法
 * @param url
 * @param data
 * @returns {Promise}
 */
export function get(url, params = {}, config = {}) {
  try {
    return service({
      url,
      params,
      method: 'GET',
      ...config,
    });
  } catch (error) {
    console.error('get:', error);
  }
}

/**
 * 封装post请求
 * @param url
 * @param data
 * @returns {Promise}
 */
export function post(url, data = {}, config = {}) {
  try {
    return service({
      url,
      method: 'POST',
      data,
      ...config,
    });
  } catch (error) {
    console.error('post:', error);
  }
}

export function del(url, data = {}, config = {}) {
  try {
    return service({
      url,
      method: 'DELETE',
      data,
      ...config,
    });
  } catch (error) {
    console.error('post:', error);
  }
}
